<template>
  <view class="orderGoods borRadius14">
<!--    <navigator v-if="orderInfo.merName" :url="`/pages/merchant/home/index?merId=`+ orderInfo.merId" hover-class="none">-->
<!--      <view class='total'>-->
<!--        <text class="mr10 iconfont icon-shangjiadingdan"></text>-->
<!--        <text class="mr10">{{ orderInfo.merName }}</text>-->
<!--        <text class="iconfont icon-xiangyou" style="font-size: 20rpx;"></text>-->
<!--      </view>-->
<!--    </navigator>-->
    <view v-show="orderData.secondType ===1" class='total'>
      <text class="mr10 iconfont icon-zhuanti"></text>
      <text class="mr10">积分商品兑换</text>
    </view>
    <view class='goodWrapper pad24'>
      <view class="item" v-for="(item,index) in cartInfo" :key="index">
        <view class='acea-row row-between-wrapper' @click="jumpCon(item)">
          <view class='pictrue'>
            <image :src='item.image'></image>
          </view>
          <view class='text'>
            <view class='acea-row row-between-wrapper'>
              <view class='name line1'>{{ item.productName }}</view>
              <view class='num line-heightOne' v-if="item.payNum">x {{ item.payNum }}</view>
            </view>

            <view class='attr' v-if="item.sku">{{ item.sku }}</view>
            <!-- 积分价格 -->
            <PointsPrice v-if="secondType === ProductTypeEnum.Integral" :pointsPrice="item"
                         :pointsGoodsStyle="hotPointsStyle" class="mt-20"></PointsPrice>
            <!-- 其他价格 -->
            <view v-else class='acea-row justify-between' style="align-items: baseline;">
              <view class="acea-row">
                <view class='money line-heightOne'>￥{{ item.price || item.productPrice }}</view>
              </view>
<!--              <view-->
<!--                  v-if="(item.deliveryMethod == 1 || !orderInfo.takeTheirSwitch) && !jump && Number(item.productType)==0"-->
<!--                  class="font-color2">不支持到店自提-->
<!--              </view>-->
<!--              <view v-if="item.deliveryMethod == 2 && !jump && Number(item.productType)==0"-->
<!--                    class="font-color2">不支持商家配送-->
<!--              </view>-->
            </view>
          </view>
        <!-- 订单状态（0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消） -->
        <view v-if="isShowBtn" class="acea-row evaluateBox">
          <view class='evaluate'
                v-if="(isRefund(item) && getApplyRefundNum(item) < item.payNum) || (refundOrderNo !=='null' && refundOrderNo !=='' && (refundOrderStatus === 0 || refundOrderStatus === 2 || refundOrderStatus === 4 || refundOrderStatus === 5))"
                @click.stop="handleRefundClick(item)">
            <text class="line-heightOne">{{ getRefundButtonText(item) }}</text>
          </view>
        </view>

      </view>
        <view class="map borRadius14" v-if="getSortedLocationList(item).length > 0">
          <view class='title item acea-row row-between-wrapper'>
            <view>适用门店</view>
            <view class="toggle-btn" @click="toggleStores" v-if="getSortedLocationList(item).length>1">
              <text>{{ showAllStores ? '收起' : '查看更多门店' }}</text>
            </view>
          </view>
          <view class="msg-content" :class="{ 'slide-down': showAllStores }">
            <view v-for="(store, idx) in (getSortedLocationList(item) || [])" :key="idx" class="store-card">
              <image class="store-img" :src="store.image" mode="aspectFill" />
              <view class="store-info">
                <view class="store-header">
                  <text class="store-title">{{ store.name }}</text>
                  <view class="store-actions">
                    <image class="icon-btn" :src="IMAGE_CONFIG.diZhi" @click.stop="openMap(store)" />
                    <image class="icon-btn" :src="IMAGE_CONFIG.dianHua" @click.stop="callStore(store.contact)" />
                  </view>
                </view>
                <view class="store-status-row">
                  <text class="store-status" :class="isStoreOpen(store) ? 'open' : 'closed'">
                    {{ isStoreOpen(store) ? '营业中' : '休息中' }}
                  </text>
                  <text class="store-time">{{ store.openTime }}-{{ store.closeTime }}</text>
                </view>
                <view class="store-address-row">
                  <text class="store-distance">{{ store.distance || '--' }}</text>
                  <text class="store-address">{{ store.address }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>

</template>

<script>

import * as filters from '@/filters'
import {
  goProductDetail
} from "../../../../libs/order";
import {
  ProductTypeEnum,
  ProductMarketingTypeEnum
} from "@/enums/productEnums";
import PointsPrice from '@/components/PointsPrice.vue';

import {IMAGE_CONFIG} from "@/utils/imageConfig";

/**
 * 积分商品推荐样式
 */
const hotPointsStyle = {
  iconStyle: {
    width: '28rpx',
    height: '28rpx'
  },
  priceStyle: {
    fontSize: '26rpx',
  },
  unitStyle: {
    fontSize: '24rpx',
  },
}
export default {
  props: {
    //订单详情
    orderData: {
      type: Object,
      default: function () {
        return {};
      }
    },
    //商品信息
    cartInfo: {
      type: Array,
      default: function () {
        return [];
      }
    },
    orderNo: {
      type: String,
      default: '',
    },
    refundOrderNo: {
      type: String,
      default: '',
    },
    refundOrderStatus: {
      type: Number,
      default: 100,
    },
    jump: {
      type: Boolean,
      default: false,
    },
    orderProNum: {
      type: Number,
      default: function () {
        return 0;
      }
    },
    //商户整条对象信息
    orderInfo: {
      type: Object,
      default: function () {
        return {};
      }
    },
    //是否显示操作按钮
    isShowBtn: {
      type: Boolean,
      default: true,
    },
    //订单二级类型:0-普通订单，1-积分订单，2-虚拟订单，4-视频号订单，5-云盘订单，6-卡密订单
    secondType: {
      type: Number,
      default: function () {
        return 0;
      }
    },
  },
  components: {
    PointsPrice
  },
  data() {
    return {
      IMAGE_CONFIG:IMAGE_CONFIG.index,
      showAllStores: false,
      hotPointsStyle: hotPointsStyle,
      totalNmu: '',
      ProductMarketingTypeEnum: ProductMarketingTypeEnum,
      ProductTypeEnum: ProductTypeEnum,
    };
  },
  watch: {
    cartInfo: function (nVal, oVal) {
      let num = 0
      nVal.forEach((item, index) => {
        num += item.cartNum
      })
      this.totalNmu = num
    }
  },
  onShow(){

  },
  methods: {
    getDistance(lat1, lng1, lat2, lng2) {
      const toRad = d => d * Math.PI / 180;
      const R = 6378137;
      const radLat1 = toRad(lat1);
      const radLat2 = toRad(lat2);
      const a = radLat1 - radLat2;
      const b = toRad(lng1) - toRad(lng2);
      const s = 2 * Math.asin(Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      ));
      return R * s;
    },
    calcAllStoreDistance(userLat,userLng) {
      console.log('[calcAllStoreDistance] userLat:', userLat, 'userLng:', userLng);
      this.cartInfo.forEach(res => {
        if (!res.locationList) {
          console.log('[calcAllStoreDistance] No locationList for cart item:', res);
          return;
        }
        res.locationList.forEach(store => {
          console.log('[calcAllStoreDistance] store:', store);
          const lat = Number(store.latitude);
          const lng = Number(store.longitude);
          console.log('[calcAllStoreDistance] lat:', lat, 'lng:', lng);
          if (lat && lng && userLat && userLng) {
            const dist = this.getDistance(userLat, userLng, lat, lng);
            store.distance = dist > 1000 ? (dist / 1000).toFixed(1) + 'km' : Math.round(dist) + 'm';
            console.log('[calcAllStoreDistance] computed distance:', store.distance);
          } else {
            store.distance = '--';
            console.log('[calcAllStoreDistance] distance set to --');
          }
        });
      });
      this.$forceUpdate && this.$forceUpdate();
    },
    // 判断门店是否营业
    isStoreOpen(store) {
      if (!store.openTime || !store.closeTime) return false;
      const now = new Date();
      const pad = n => n < 10 ? '0' + n : n;
      const nowStr = pad(now.getHours()) + ':' + pad(now.getMinutes());
      // 营业时间可能跨天
      if (store.openTime < store.closeTime) {
        // 正常营业时间
        return nowStr >= store.openTime && nowStr < store.closeTime;
      } else {
        // 跨天营业（如22:00-06:00）
        return nowStr >= store.openTime || nowStr < store.closeTime;
      }
    },
    callStore(phone) {
      if (!phone) return;
      uni.makePhoneCall({ phoneNumber: phone + '' });
    },
    // 跳转到微信地图
    openMap(store) {
      if (!store.latitude || !store.longitude) {
        this.$util && this.$util.Tips ? this.$util.Tips({ title: '门店未配置坐标' }) : uni.showToast({ title: '门店未配置坐标', icon: 'none' });
        return;
      }
      uni.openLocation({
        latitude: Number(store.latitude),
        longitude: Number(store.longitude),
        name: store.name,
        address: store.address
      });
    },
    toggleStores() {
      this.showAllStores = !this.showAllStores;
    },
    // 普通商品、虚拟（开启可申请退款开关）、视频号可申请退款
    isRefund(item) {
      return (this.secondType === this.ProductTypeEnum.Normal || this
          .secondType === this.ProductTypeEnum.Video || (this.secondType === this.ProductTypeEnum.Fictitious && item.proRefundSwitch)) && this.orderData.status > 0 && this.orderData.status < 6;
    },
    // 退款数量
    getApplyRefundNum(item) {
      return Number(item.applyRefundNum) + Number(item.refundNum)

    },
    /**
     * 退款申请
     */
    goRefund(item) {
      item.groupBuyActivityId = this.orderData.groupBuyActivityId
      this.$Cache.set('productInfo', item)
      uni.navigateTo({
        url: '/pages/goods/after_sales_type/index?orderNo=' + this.orderNo + '&orderId=' + item.id
      })
    },
    /**
     * 退款详情
     */
    goRefundOrder(item) {
      uni.navigateTo({
        url: '/pages/goods/refund_details/index?refundOrderNo=' + item
      })
    },
    jumpCon: function (item) {
      let type = item.hasOwnProperty('productMarketingType') ? item.productMarketingType : item.hasOwnProperty('productType') ? item.productType : item.type;
      if (this.jump) {
        // goProductDetail(item.productId, type, '')
        uni.navigateTo({
          url: '/pages/discover/courseDetails/index?id=' + item.productId
        })
      }
    },
    getSortedLocationList(item) {
      console.log(item)
      console.log(this.cartInfo)
      console.log(item.locationList)
      return (item.locationList || []).slice().sort((a, b) => {
        const da = Number(a.distance) || Infinity;
        const db = Number(b.distance) || Infinity;
        return da - db;
      });
    },
    getRefundButtonText(item) {
      if (
        this.refundOrderNo !== 'null' &&
        this.refundOrderNo !== '' &&
        (this.refundOrderStatus === 0 ||
          this.refundOrderStatus === 2 ||
          this.refundOrderStatus === 4 ||
          this.refundOrderStatus === 5)
      ) {
        return '退款详情';
      }
      if (this.isRefund(item) && this.getApplyRefundNum(item) < item.payNum) {
        return '申请退款';
      }
      return '';
    },
    handleRefundClick(item) {
      const btnText = this.getRefundButtonText(item);
      if (btnText === '退款详情') {
        this.goRefundOrder(this.refundOrderNo);
      } else if (btnText === '申请退款') {
        this.goRefund(item);
      }
    }
  }
}
</script>

<style scoped lang="scss">
.evaluateBox {
  position: relative;
  margin-top: 10rpx;

  .text {
    font-size: 20rpx;
    color: #868686;
  }
}

.evaluate {
  width: 130rpx !important;
  bottom: -40rpx !important;
  border-radius: 20rpx !important;
  padding: 0 10rpx;
  font-size: 24rpx;
}

.pad24 {
  padding: 20rpx 24rpx 20rpx 24rpx;
}

.orderGoods {
  background-color: #fff;
  margin-top: 24rpx;
}

.money {
  //@include price_color(theme);
  color: #FF4B4B;
}
.font-color2{
  color: #FF4B4B;
}

.orderGoods .total {
  width: 100%;
  height: 86rpx;
  padding: 0 24rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 30rpx;
  color: #282828;
  line-height: 86rpx;
  box-sizing: border-box;
}

.pictrue image {
  background: #f4f4f4;
}

.goodWrapper {
  .item {
    margin: 30rpx 0 10rpx;
  }

  .item:nth-last-child(1) {
    margin-bottom: 0;
  }

  .name {
    width: 87%;
  }
}
.msg-content {
  max-height: 224rpx;
  opacity: 0.85;
  overflow: hidden;
  padding-top: 8px;
  padding-bottom: 0;
  transition: all 0.4s cubic-bezier(.55,0,.1,1);
}
.msg-content.slide-down {
  max-height: 1000px;
  opacity: 1;
}
.store-card {
   display: flex;
   align-items: flex-start;
   border-radius: 16px;
   box-shadow: 0 2px 8px #f3f1ed;
   padding: 20rpx 24rpx;
   margin: 20rpx 0;
   .store-img {
     width: 100rpx;
     height: 100rpx;
     margin-top: 10rpx;
     border-radius: 12rpx;
     object-fit: cover;
     flex-shrink: 0;
     margin-right: 20rpx;
   }
   .store-info {
     flex: 1;
     min-width: 0;
     .store-header {
       display: flex;
       align-items: flex-start;
       justify-content: space-between;
       .store-title {
         font-weight: bold;
         color: #222;
         flex: 1;
         min-width: 0;
         overflow: hidden;
         text-overflow: ellipsis;
         white-space: nowrap;
       }
       .store-actions {
         display: flex;
         align-items: center;
         margin-left: 12rpx;
         .icon-btn {
           width: 30rpx;
           height: 30rpx;
           margin-left: 20rpx;
         }
       }
     }
     .store-status-row {
       margin-top: 8rpx;
       display: flex;
       align-items: center;
       .store-status {
         color: #888;
         font-size: 26rpx;
         margin-right: 16rpx;
         &.open { color: #8a4513; font-weight: bold; }
         &.closed { color: #bbb; }
       }
       .store-time {
         color: #888;
         font-size: 26rpx;
       }
     }
     .store-address-row {
       margin-top: 8rpx;
       display: flex;
       align-items: center;
       .store-distance {
         color: #e94f6a;
         font-size: 28rpx;
         margin-right: 12rpx;
         font-weight: 500;
       }
       .store-address {
         color: #888;
         font-size: 28rpx;
         overflow: hidden;
         text-overflow: ellipsis;
         white-space: nowrap;
         flex: 1;
       }
     }
   }
 }
</style>